import logging
import os
from datetime import datetime
import sys
import json
from icecream import ic

from get_sql_res import gen_run_detail
from gen_info_dic import gen_info_dic
from excel_write_in import write_in_tables,write_in_figs
from excel_decorate_base import decorate_base_sheet
from excel_decorate_detail_sheet import decorate_rule_detail
from gen_fig import gen_figs

if not os.path.exists('./logs'):
    os.makedirs('./logs')

current_time = datetime.now().strftime("%m_%d_%H_%M")
logging.basicConfig(filename=f'./logs/{current_time}.log', level=logging.DEBUG)
def gen_report(rule_run_record_id,re_file_path,sql_info):
    # 获取基本信息
    df_run_detail,df_run_detail_raw = gen_run_detail(rule_run_record_id,sql_info)
    info_dic=gen_info_dic(df_run_detail,sql_info)
    logging.info(f"rule_run_record_id:{rule_run_record_id}")
    logging.info(f"{info_dic}")
    logging.info('获取基本信息成功')
    # 写入准备好的df
    write_in_tables(re_file_path, info_dic, df_run_detail,sql_info,df_run_detail_raw)
    logging.info('表格写入excel成功')
    # 装饰base_sheet
    decorate_base_sheet(re_file_path, info_dic)
    # 装饰rule_detail相关sheet
    decorate_rule_detail(info_dic, re_file_path)
    logging.info('装饰excel成功')
    # 为MAP这个sheet写入图片
    path_dic=gen_figs(df_run_detail,info_dic,sql_info)
    write_in_figs(path_dic,re_file_path,info_dic)
    logging.info('写入图片成功')
    logging.info('报告生成成功')


if __name__ == '__main__':

    with open('./input/aaa.json', 'r') as file:
        input = json.load(file)
    rule_run_record_id = input['recordId']
    sql_info = {}
    sql_info['mysqlInfo'] = input['mysqlInfo']
    sql_info['ckInfo'] = input['ckInfo']
    sql_info['dasHost'] = input['dasHost']
    sql_info['reportHost'] = input['reportHost']
    re_file_path = input['fileFullPath']
    ##
    # gen_report(rule_run_record_id, re_file_path, sql_info)
    try:
        gen_report(rule_run_record_id,re_file_path,sql_info)
        res={
            "code":"",
            "data": [{
                    "fileName":input['fileFullPath'],
                    "fileType":"",
                    "fileFullPath":""}],
            "msg":""}
        print(json.dumps(res))
    except Exception as e:
        print(f"An error occurred: {e}")

